package auth

import (
	"github.com/astaxie/beego/orm"
)

type User struct {
	ID        int     `json:"id" orm:"column(id);unique"`
	UUID      string  `json:"uuid" orm:"column(uuid);unique"`
	Name      string  `json:"name" orm:"unique"`
	Password  string  `json:"password" orm:"type(text)"`
	Role      []*Role `json:"role" orm:"rel(m2m)"`
	TruthName string  `json:"truthname"`
	Email     string  `json:"email"`
	PhoneNum  string  `json:"phonenum"`
	Group     *Group  `json:"group" orm:"rel(fk)"`
}

func GetUserByName(o orm.Ormer, name string) (User, error) {
	user := User{}
	err := o.QueryTable(User{}).Filter("name", name).One(&user)
	if err != nil {
		return User{}, err
	}
	_, err = o.LoadRelated(&user, "role")
	if err != nil {
		return user, err
	}
	return user, nil
}

func GetUserByUUID(o orm.Ormer, uuid string) (User, error) {
	user := User{}
	err := o.QueryTable(User{}).Filter("uuid", uuid).One(&user)
	if err != nil {
		return User{}, err
	}
	_, err = o.LoadRelated(&user, "role")
	if err != nil {
		return user, err
	}
	_, err = o.LoadRelated(&user, "group")
	if err != nil {
		return user, err
	}
	return user, nil
}

func UpdateUser(o orm.Ormer, user User) error {
	// TODO
	return nil
	//oldUser := User{Id:user.Id}
	//o.Read(oldUser.Id)
	//_, err := o.Update(&user)
	//_, err = o.QueryM2M(&user, "role").Clear()
	//if err != nil {
	//	return err
	//}
	//for _, role := range user.Role {
	//	roleData := Role{Id:role.Id}
	//	err = o.Read(&roleData)
	//	if err != nil {
	//		return err
	//	}
	//	_, err = o.QueryM2M(&user, "role").Add(roleData)
	//	if err != nil {
	//		return err
	//	}
	//}
	//
	//groupData := Group{Id:user.Id}
	//err = o.Read(&groupData)
	//if err != nil {
	//	return err
	//}
	//_, err = o.QueryM2M(&user, "role").Clear()
	//if err != nil {
	//	return err
	//}

	//return err
}

func DeleteUserByName(o orm.Ormer, name string) error {
	user := User{Name: name}
	_, err := o.Delete(&user)
	return err
}

func CreateUser(o orm.Ormer, user User) (User, error) {
	_, err := o.Insert(user)
	if err != nil {
		return user, err
	}
	return GetUserByName(o, user.Name)
}

func ListUsers(o orm.Ormer, filter string) ([]User, error) {
	users := []User{}
	_, err := o.QueryTable(User{}).Filter(filter).All(&users)
	return users, err
}
